<template>
  <div class="dealer-list-page">
    <div class="header">
      <h2>授权经销商</h2>
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索经销商名称或地址"
          clearable
          @clear="fetchDealers"
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="dealer-grid" v-loading="loading">
      <el-empty v-if="dealerList.length === 0" description="暂无经销商" />
      
      <el-card 
        v-for="dealer in dealerList" 
        :key="dealer.id" 
        class="dealer-card"
        shadow="hover"
        @click="handleViewDetail(dealer)"
      >
        <div class="dealer-card-content">
          <div class="dealer-logo">
            <el-image 
              :src="dealer.logo || defaultLogo" 
              fit="cover"
              :fallback-src="defaultLogo"
            />
          </div>
          <div class="dealer-info">
            <h3>{{ dealer.dealerName }}</h3>
            <p class="address">
              <el-icon><Location /></el-icon>
              {{ dealer.address }}
            </p>
            <p class="contact">
              <el-icon><Phone /></el-icon>
              {{ dealer.contactPhone }}
            </p>
            <p class="contact-person">
              <el-icon><User /></el-icon>
              联系人: {{ dealer.contactPerson }}
            </p>
          </div>
        </div>
        <div class="dealer-description">
          {{ dealer.description || '暂无描述' }}
        </div>
      </el-card>
    </div>

    <el-pagination
      v-if="total > 0"
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[8, 16, 24, 32]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 经销商详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="经销商详情"
      width="700px"
    >
      <div v-if="selectedDealer" class="dealer-detail">
        <div class="dealer-header">
          <div class="dealer-logo-large">
            <el-image 
              :src="selectedDealer.logo || defaultLogo" 
              fit="cover"
              :fallback-src="defaultLogo"
            />
          </div>
          <div class="dealer-title">
            <h2>{{ selectedDealer.dealerName }}</h2>
            <el-tag type="success">授权经销商</el-tag>
          </div>
        </div>

        <el-descriptions :column="2" border class="dealer-specs">
          <el-descriptions-item label="营业执照">{{ selectedDealer.businessLicense }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedDealer.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ selectedDealer.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="成立时间">{{ formatDate(selectedDealer.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ selectedDealer.address }}</el-descriptions-item>
        </el-descriptions>

        <div class="dealer-section">
          <h3>经销商介绍</h3>
          <p>{{ selectedDealer.description || '暂无介绍' }}</p>
        </div>

        <div class="dealer-actions">
          <el-button type="primary" @click="makeAppointment">
            <el-icon><Calendar /></el-icon> 预约看车
          </el-button>
          <el-button @click="callDealer">
            <el-icon><Phone /></el-icon> 电话咨询
          </el-button>
          <el-button @click="navigateToDealer">
            <el-icon><Location /></el-icon> 导航前往
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAllDealers, getDealersByPage, searchDealers } from '@/api/dealer'
import { Search, Location, Phone, User, Calendar } from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const dealerList = ref([])
const page = ref(1)
const pageSize = ref(8)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const selectedDealer = ref(null)

const defaultLogo = 'https://via.placeholder.com/150?text=No+Logo'

// 获取经销商列表
const fetchDealers = async () => {
  loading.value = true
  try {
    if (searchQuery.value) {
      // 搜索模式
      const params = {
        dealerName: searchQuery.value,
        address: searchQuery.value
      }
      const response = await searchDealers(params)
      dealerList.value = response || []
      total.value = dealerList.value.length
    } else {
      // 分页模式
      const response = await getDealersByPage(page.value, pageSize.value)
      dealerList.value = response.data || []
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('获取经销商列表失败:', error)
    ElMessage.error('获取经销商列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  page.value = 1
  fetchDealers()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未知'
  return new Date(date).toLocaleDateString()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchDealers()
}

// 页码变化
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  fetchDealers()
}

// 查看经销商详情
const handleViewDetail = (dealer) => {
  selectedDealer.value = dealer
  dialogVisible.value = true
}

// 预约看车
const makeAppointment = () => {
  if (!selectedDealer.value) return
  
  // 这里可以跳转到预约页面，传递经销商ID
  router.push({
    path: '/appointment',
    query: { dealerId: selectedDealer.value.id }
  })
  
  dialogVisible.value = false
}

// 拨打电话
const callDealer = () => {
  if (!selectedDealer.value) return
  
  // 这里可以直接使用tel协议拨打电话
  window.location.href = `tel:${selectedDealer.value.contactPhone}`
}

// 导航前往
const navigateToDealer = () => {
  if (!selectedDealer.value) return
  
  // 这里可以打开地图应用进行导航
  const address = encodeURIComponent(selectedDealer.value.address)
  window.open(`https://maps.google.com/?q=${address}`, '_blank')
}

onMounted(() => {
  fetchDealers()
})
</script>

<style scoped>
.dealer-list-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 28px;
  color: #303133;
}

.search-bar {
  width: 300px;
}

.search-icon {
  cursor: pointer;
}

.dealer-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.dealer-card {
  cursor: pointer;
  transition: transform 0.3s;
  height: 100%;
}

.dealer-card:hover {
  transform: translateY(-5px);
}

.dealer-card-content {
  display: flex;
  margin-bottom: 10px;
}

.dealer-logo {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 5px;
  overflow: hidden;
}

.dealer-info {
  flex: 1;
}

.dealer-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
}

.address, .contact, .contact-person {
  display: flex;
  align-items: center;
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}

.address .el-icon, .contact .el-icon, .contact-person .el-icon {
  margin-right: 5px;
}

.dealer-description {
  color: #909399;
  font-size: 14px;
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 详情弹窗样式 */
.dealer-detail {
  padding: 20px 0;
}

.dealer-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.dealer-logo-large {
  width: 120px;
  height: 120px;
  margin-right: 20px;
  border-radius: 5px;
  overflow: hidden;
}

.dealer-title {
  flex: 1;
}

.dealer-title h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.dealer-specs {
  margin-bottom: 20px;
}

.dealer-section {
  margin-bottom: 20px;
}

.dealer-section h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.dealer-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}
</style> 